use crate::pojo::dto::ConfigDto;
use std::error::Error;
use std::fs;

pub mod pojo;

// 测试用例
#[cfg(test)]
mod tests{
    use super::*;
    #[test]
    fn one_result(){
        let query = "safe";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";
        assert_eq!(vec!["safe, fast, productive."],search(query, contents))
    }
}

pub fn run(config: ConfigDto) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;
    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    }else{
        search(&config.query, &contents)
    };
    println!("检索结果:\n");
    
    for ele in results {
        println!("{ele}");
    }
    Ok(())
}

/// 返回匹配的行
/// 
/// # 例子
/// ```
/// let query = "duct";
/// let contents = "safe, fast, productive.";
/// assert_eq!(vec!["safe, fast, productive."],search(query, contents));
/// ```
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
    .lines()
    .filter(|line| line.contains(query))
    .collect()
}

fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();
    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }
    results
}
    
